package com.handu.luna.boss.controller;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Base64;
import java.util.List;

import javax.validation.Valid;

import net.sf.json.JSONObject;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Iterator;

import org.apache.poi.ss.usermodel.Row;

import com.handu.luna.core.domain.goods.Goods;
import com.handu.luna.core.domain.promotion.SalesPromotionGoods;
import com.handu.luna.core.domain.searchVo.GoodsSearch;
import com.handu.luna.core.domain.support.FileUploadSupport;
import com.handu.luna.core.domain.support.FileUploadSupport.FileType;


@Controller
@RequestMapping("/promotion/salespromotiongoods/*")
public class SalesPromotionGoodsController extends BaseController{
	
	@RequestMapping(value = {"index/{salesPromotionId}","/",""})
    public BossModel index(@PathVariable int salesPromotionId,String viewState,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable){
		if(viewState == null || viewState.equals("")){
			return createModel("promotion/salespromotiongoods/index")
					.add("salespromotiongoodsPage",context.getSalesPromotionGoodsRepository().findBySalesPromotionId(salesPromotionId,pageable))
					.add("viewState", "")
					.add("salesPromotionId", salesPromotionId);

		}else{
			return createModel("promotion/salespromotiongoods/index")
					.add("salespromotiongoodsPage",context.getSalesPromotionGoodsRepository().findBySalesPromotionId(salesPromotionId, pageable))
					.add("viewState", viewState)
					.add("salesPromotionId", salesPromotionId);
		}
	}
	
	@RequestMapping(value="add/{salesPromotionId}")
	public BossModel add(@PathVariable String salesPromotionId){

		return createModel("promotion/salespromotiongoods/addinfo").add("goodsSearch", new GoodsSearch())
				.add("salesPromotionId", salesPromotionId)
				.add("brands", context.getBrandRepository().findAll())
				.add("categorys", context.getCategoryRepository().findAll());
	}
	
	@RequestMapping(value="edit/{salesPromotionId}/{id}")
	public BossModel add(@PathVariable String salesPromotionId,@PathVariable long id){

		return createModel("promotion/salespromotiongoods/edit").add("spg", context.getSalesPromotionGoodsRepository().findOne(id))
				.add("salesPromotionId", salesPromotionId);
	}
	
	/**
	 * 查询商品展示(post提交查询)
	 * @param pageable
	 * @param salesPromotionId
	 * @param goodsSearch
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "list/{salesPromotionId}",method=RequestMethod.POST)
	public BossModel list(@PathVariable long salesPromotionId,GoodsSearch goodsSearch,@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE) Pageable pageable)throws UnsupportedEncodingException {

		
		Page<Goods> goodsList = context.getGoodsRepository().findAll(new Goods().selectCondition(goodsSearch),pageable);
		for (Goods good :goodsList) {
			SalesPromotionGoods spgood = context.getSalesPromotionGoodsRepository().findBySalesPromotionIdAndGoodsId(salesPromotionId, good.getId());
			if(spgood == null){
				good.setPromotion(0);
			}else{
				good.setPromotion(1);
				good.setPromotionPrice(spgood.getGoodsPrice());
			}
		}
		
		return createModel("promotion/salespromotiongoods/info").add("goodsPage",goodsList)
				.add("goodsSearch", goodsSearch)
				.add("salesPromotionId", salesPromotionId)
				.add("brands", context.getBrandRepository().findAll())
				.add("categorys", context.getCategoryRepository().findAll())
				.add("viewState", Base64.getEncoder().encodeToString(JSONObject.fromObject(goodsSearch).toString().getBytes("UTF-8")));
			
	}
	
	/**
	 * 查询商品展示(带参数翻页调用)
	 * @param pageable
	 * @param salesPromotionId
	 * @param viewState
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "list/{salesPromotionId}",method=RequestMethod.GET)
	public BossModel list(String viewState,@PathVariable long salesPromotionId,@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE) Pageable pageable)throws UnsupportedEncodingException {

		GoodsSearch search;
		if(viewState != null && !viewState.trim().equals("")){
			//解析传递过来的查询json字符串
			search = (GoodsSearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getDecoder().decode(viewState),"UTF-8")), GoodsSearch.class);
		}else{
			search = new GoodsSearch();
		}
		Page<Goods> goodsList = context.getGoodsRepository().findAll(new Goods().selectCondition(search),pageable);
		for (Goods good :goodsList) {
			SalesPromotionGoods spgood = context.getSalesPromotionGoodsRepository().findBySalesPromotionIdAndGoodsId(salesPromotionId, good.getId());
			if(spgood== null){
				good.setPromotion(0);
			}else{
				good.setPromotion(1);
				good.setPromotionPrice(spgood.getGoodsPrice());
			}
		}
		if(viewState != null && !viewState.trim().equals("")){
			return createModel("promotion/salespromotiongoods/info").add("goodsPage",goodsList)
					.add("goodsSearch", search)
					.add("salesPromotionId", salesPromotionId)
					.add("brands", context.getBrandRepository().findAll())
					.add("categorys", context.getCategoryRepository().findAll())
					.add("viewState", viewState);
		}else{
			return createModel("promotion/salespromotiongoods/info").add("goodsPage",goodsList)
					.add("goodsSearch", search)
					.add("salesPromotionId", salesPromotionId)
					.add("brands", context.getBrandRepository().findAll())
					.add("categorys", context.getCategoryRepository().findAll())
					.add("viewState", "");
		}
			
	}
	
	@RequestMapping(value="save/{salesPromotionId}",method = RequestMethod.POST)
	@InitBinder(value={"goodsPrice"})
	public BossModel save(@Valid @ModelAttribute("spg") final SalesPromotionGoods spg,@PathVariable int salesPromotionId,final BindingResult bindingResult, RedirectAttributes redirectAttributes, @PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable){
		if(spg.getGoodsPrice() == null) {
			bindingResult.rejectValue("goodsPrice", "", "请输入促销价格");
		}
		if (bindingResult.hasErrors()) {
			return createModel("promotion/salespromotiongoods/edit")
					.add("spg", context.getSalesPromotionGoodsRepository().findOne(spg.getId()))
					.add("salesPromotionId", salesPromotionId);			
		}
		String messagePrefix = spg.getSucessFlashMessage();
		context.getSalesPromotionGoodsRepository().save(spg);
		return createModel("promotion/salespromotiongoods/index")
				.add("salespromotiongoodsPage",context.getSalesPromotionGoodsRepository().findBySalesPromotionId(salesPromotionId,pageable))
				.add("viewState", "")
				.add("salesPromotionId", salesPromotionId)
				.add("message", messagePrefix);
	}
	
	@RequestMapping(value="ajaxsave",method = RequestMethod.POST)
	public BossModel save(String viewState,long id, BigDecimal price, int spid, @PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable) throws UnsupportedEncodingException{
		//List<SalesPromotionGoods> goodsCheck = context.getSalesPromotionGoodsRepository().findBySalesPromotionIdAndGoodsId(spid, id);
		List<Goods> goodsCheckDelete = context.getGoodsRepository().findUnTrash(id);
		if(!goodsCheckDelete.isEmpty()){
			SalesPromotionGoods spgoods = new SalesPromotionGoods();
			spgoods.setSalesPromotionId(spid);
			spgoods.setGoodsPrice(price);
			spgoods.setGoodsId(id);
			context.getSalesPromotionGoodsRepository().save(spgoods);
		}

		GoodsSearch search;
		if(viewState != null && !viewState.trim().equals("")){
			//解析传递过来的查询json字符串
			search = (GoodsSearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getDecoder().decode(viewState),"UTF-8")), GoodsSearch.class);
		}else{
			search = new GoodsSearch();
		}
		Page<Goods> goodsList = context.getGoodsRepository().findAll(new Goods().selectCondition(search),pageable);
		for (Goods good :goodsList) {
			SalesPromotionGoods spgood = context.getSalesPromotionGoodsRepository().findBySalesPromotionIdAndGoodsId(spid, good.getId());
			if(spgood == null){
				good.setPromotion(0);
			}else{
				good.setPromotion(1);
				good.setPromotionPrice(spgood.getGoodsPrice());
			}
		}
		if(viewState != null && !viewState.trim().equals("")){
			return createModel("promotion/salespromotiongoods/goods_table").add("goodsPage",goodsList)
					.add("goodsSearch", search)
					.add("salesPromotionId", spid)
					.add("viewState", viewState);
		}else{
			return createModel("promotion/salespromotiongoods/goods_table").add("goodsPage",goodsList)
					.add("goodsSearch", search)
					.add("salesPromotionId", spid)
					.add("viewState", "");
		}
	}
		
	@RequestMapping(value="uploadgoods/{salesPromotionId}",method= RequestMethod.POST)
	public BossModel uploadgoods(@PathVariable long salesPromotionId,@RequestParam("goodsFile") MultipartFile goodsFile, @PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable) throws FileNotFoundException, IOException{
		if(!goodsFile.getOriginalFilename().equals("")){
			String fileName[] = goodsFile.getOriginalFilename().split("\\.");
			if(fileName[1].equals("xls")){
				
	            String fileUrl = FileUploadSupport.uploadFile(goodsFile.getInputStream(), goodsFile.getOriginalFilename(), FileType.XLS);
				
				HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(fileUrl));
				HSSFSheet sheet = wb.getSheetAt(0);
				//迭代行
				for (Iterator<Row> iter = (Iterator<Row>) sheet.rowIterator(); iter.hasNext();) {
				        Row row = iter.next();
				        String goods_sn = row.getCell(0).toString();
				        BigDecimal goods_price = BigDecimal.valueOf(row.getCell(1).getNumericCellValue());
				        
				        List<Goods> goods = context.getGoodsRepository().findByGoodsSN(goods_sn);
				        if(!goods.isEmpty()){
				        	SalesPromotionGoods goodsCheck = context.getSalesPromotionGoodsRepository().findBySalesPromotionIdAndGoodsId(salesPromotionId, goods.get(0).getId());
				        	if(goodsCheck == null){
				        		SalesPromotionGoods spgoods = new SalesPromotionGoods();
								spgoods.setSalesPromotionId(salesPromotionId);
								spgoods.setGoodsPrice(goods_price);
								spgoods.setGoodsId(goods.get(0).getId());
								context.getSalesPromotionGoodsRepository().save(spgoods);
				        	}
				        }
				}
			}
		}
		
		return createModel("promotion/salespromotiongoods/index")
				.add("salespromotiongoodsPage",context.getSalesPromotionGoodsRepository().findBySalesPromotionId(salesPromotionId,pageable))
				.add("viewState", "")
				.add("salesPromotionId", salesPromotionId);
	}
	
	@RequestMapping(value="delete",method= RequestMethod.POST)
	public BossModel delete(long id, long spid, @PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable){
		context.getSalesPromotionGoodsRepository().delete(id);
		return createModel("promotion/salespromotiongoods/salespromotiongoods_table")
				.add("salespromotiongoodsPage",context.getSalesPromotionGoodsRepository().findBySalesPromotionId(spid,pageable))
				.add("viewState", "")
				.add("salesPromotionId", spid);
	}
	
	@RequestMapping(value="deletegood",method= RequestMethod.POST)
	public BossModel deletegood(String viewState,long goodsId, int spid, @PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable) throws UnsupportedEncodingException{
		context.getSalesPromotionGoodsRepository().deleteByPromotionIdAndGoodsId(spid, goodsId);
		
		
		GoodsSearch search;
		if(viewState != null && !viewState.trim().equals("")){
			//解析传递过来的查询json字符串
			search = (GoodsSearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getDecoder().decode(viewState),"UTF-8")), GoodsSearch.class);
		}else{
			search = new GoodsSearch();
		}
		Page<Goods> goodsList = context.getGoodsRepository().findAll(new Goods().selectCondition(search),pageable);
		for (Goods good :goodsList) {
			SalesPromotionGoods  spgood = context.getSalesPromotionGoodsRepository().findBySalesPromotionIdAndGoodsId(spid, good.getId());
			if(spgood == null){
				good.setPromotion(0);
			}else{
				good.setPromotion(1);
				good.setPromotionPrice(spgood.getGoodsPrice());
			}
		}
		if(viewState != null && !viewState.trim().equals("")){
			return createModel("promotion/salespromotiongoods/goods_table").add("goodsPage",goodsList)
					.add("goodsSearch", search)
					.add("salesPromotionId", spid)
					.add("viewState", viewState);
		}else{
			return createModel("promotion/salespromotiongoods/goods_table").add("goodsPage",goodsList)
					.add("goodsSearch", search)
					.add("salesPromotionId", spid)
					.add("viewState", "");
		}
	}
}
